package cn.wolfcode.transfer.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.wolfcode.transfer.domain.Appointment;
import cn.wolfcode.transfer.domain.Consumption;
import cn.wolfcode.transfer.mapper.ConsumptionMapper;
import cn.wolfcode.transfer.qo.QueryObject;
import cn.wolfcode.transfer.service.IAppointmentService;
import cn.wolfcode.transfer.service.IConsumptionService;
import cn.wolfcode.transfer.util.ConsumptionStatusUtil;
import cn.wolfcode.transfer.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ConsumptionServiceImpl implements IConsumptionService {

    @Autowired
    private ConsumptionMapper consumptionMapper;
@Autowired
private IAppointmentService appointmentService;

    @Override
    public void save(Consumption consumption) {
        consumptionMapper.insert(consumption);
    }

    @Override
    public void delete(Long id) {
        consumptionMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Consumption consumption) {
        consumptionMapper.updateByPrimaryKey(consumption);
    }

    @Override
    public Consumption get(Long id) {
        return consumptionMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Consumption> listAll() {
        return consumptionMapper.selectAll();
    }

    @Override
    public PageInfo<Consumption> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Consumption> consumptions = consumptionMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Consumption>(consumptions);
    }

    @Override
    public Consumption ByAnoInsert(String ano) {
        Appointment appointment = appointmentService.ByAno(ano);
        Consumption consumption = new Consumption();
        consumption.setCno(DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomNumbers(5));
        consumption.setStatus(ConsumptionStatusUtil.待结算.getValue());
        consumption.setCustomerName(appointment.getContactName());
        consumption.setCustomerTel(appointment.getContactTel());
        consumption.setAppointment(appointment);
        consumption.setCheckinTime(new Date());
        consumption.setCreateTime(new Date());
        consumption.setBusiness(appointment.getBusiness());
        consumption.setCreateUser(UserContext.getCurrentUser());
        consumptionMapper.insert(consumption);
        return consumption;
    }
}
